//https://leetcode.cn/problems/3sum/
package codeRandomThoughts.Test15三数之和;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution2 {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> results = new ArrayList<>();

        //首先对数组递增排序
        Arrays.sort(nums);

        //双指针
        int left = 0;
        int right = nums.length - 1;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > 0) {
                //因为数组是递增排序
                return results;
            }

            //这一步是为了去除i的重复
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }

            left = i + 1;
            right = nums.length - 1;

            while (right > left) {
                int sum = nums[i] + nums[left] + nums[right];
                if (sum > 0) {
                    right--;
                } else if (sum < 0) {
                    left++;
                } else {
                    List<Integer> result = new ArrayList<>();
                    result.add(nums[i]);
                    result.add(nums[left]);
                    result.add(nums[right]);
                    results.add(result);

                    //对left和right进行去重操作,这里&&前面的是精华,加了
                    //right>left这个条件就不用担心乱七八糟的越界了
                    while (right > left && nums[right] == nums[right - 1]) right--;
                    while (right > left && nums[left] == nums[left + 1]) left++;

                    //左右指针都要往中间移动
                    right--;
                    left++;
                }
            }
        }
        return results;
    }
}
